package api
{
	import SEApp.se_app;
	
	import UIUtils.uif_json;
	
	import api_servers.api_externalserver;
	
	import flash.events.Event;
	import flash.utils.ByteArray;
	
	import ru.inspirit.net.MultipartURLLoader;

	public class clt_vkserverAPI extends api_externalserver {
		private var _flashVars: Object;
		private var _wrapper: Object;
		public function clt_vkserverAPI(a_sroot: se_app): void {
 			_wrapper = Object(a_sroot.parent.parent);			
			_flashVars = _wrapper.application.parameters;
//access_token=6966419d25c9eec46b9807e9036be4955dd6bc76bc7497abc8b492b498710b5&api_id=2350118&api_settings=1&api_url=http%3A%2F%2Fapi.vkontakte.ru%2Fapi.php&auth_key=939e64b259975b1a4046b26321699ce2&group_id=0&hash=&is_app_user=1&language=0&lc_name=eeca3451&parent_language=0&referrer=profile&secret=f53aa17b71&sid=d93286dc68667c186335b46e4fc6d2709f2761bb88d4236a72c3fb11f7dd1c&user_id=44108006&viewer_id=44108006&viewer_type=2			
			if (!_flashVars.api_id) {
				_flashVars['api_id'] = 2350118;
				_flashVars['viewer_id'] = 44108006;
				_flashVars['sid'] = "d93286dc68667c186335b46e4fc6d2709f2761bb88d4236a72c3fb11f7dd1c";
				_flashVars['secret'] = "f53aa17b71";
			}
			
			if (_flashVars['api_result']) _flashVars['api_result'] = uif_json.d(_flashVars['api_result']).response;
			
			
			super(a_sroot, 'http://api.vkontakte.ru/api.php', _flashVars['viewer_id'], _flashVars['api_id'], _flashVars['secret'], 1000);
		}
		
		override public function convertVars(): Object {
			return {
				'photo'			: {name:'pic_small'},
				'photo_medium'	: {name:'pic'},
				'photo_big'		: {name:'pic_big'},
				'src_big'		: {name:'src'},
				'src_xbig'		: {name:'src'},
				'src_xxbig'		: {name:'src'},
				'nickname'		: {name:'nick'},
				'sex': {name:'sex', cnv: function(val: uint): uint {
							return (val==0)?1:(2 - val); // Приведение к стандарту моего мира: 0- мужчина, 1-женщина
						}
				},
				'privacy': {name:'privacy', cnv: function(val: String): uint {
												switch (parseInt(val)) {
													case 0: return 2;
													case 1: return 4;
													case 2: return 0;
												}
												return parseInt(val);
											}
							}
			}			
		}
		
/*		
		override protected function srHelper( arr:Array): URLVariables {// sendRequestHelper
			arr.push( {pn: "api_id", pv: app_id } );
			arr.push( {pn: "v", pv: '3.0' } );
			arr.push( {pn: "format", pv: 'JSON' } );
					  
			arr.sortOn('pn');
					  
			var url_vars:URLVariables = new URLVariables();
			for( var i: int = 0; i < arr.length; i++ ) {
				url_vars[ (arr[i].pn) ] = arr[ i ].pv;
			}
					  
			url_vars["sig"] = makeSig(arr);
			url_vars["sid"] = _flashVars['sid'];
			return url_vars;
		}
	    
	    override protected function prepareData(a_queryID:String, data:*):* {
	    	if (data.error) {
	    		sroot.alert(sroot.classes.locale.ERROR, 'Код ошибки: ' + data.error + '\n' + data.error.error_msg);
	    		return null;
	    	} else if (data.response) return data.response;
	    	return null;
	    }*/
	    
	    protected function doApiError(data: Object): void {
	    	if (data.error_code != 10007)
	    		sroot.alert(sroot.classes.locale.ERROR, 'Код ошибки: ' + data.error_code + '\n' + data.error_msg);
	    }
	    
		override public function get flashVars(): Object {
			return _flashVars;
		}
		
		public function get wrapper(): Object {
			return _wrapper;
		}
		
		protected function callJS(method: String, event: String, _handle: Function, ...params): void {
			function doEvent(e: Object): void {
				if (event) wrapper.removeEventListener(event, doEvent);
				if (_handle != null) _handle(e);
			}
			if (event) wrapper.addEventListener(event, doEvent);
			wrapper.external.callMethod(method, params);
		}
		
		protected function callAPI(method: String, params: Object, handler_: Function, onError: Function=null): void {
			sroot.dispatchEvent(new GDataEvent(GDataEvent.REQUEST, null));
			wrapper.external.api(method, params, function(data: Object): void {
				handler_(prepareData('', data));
				sroot.dispatchEvent(new GDataEvent(GDataEvent.RESPONSE, null));
			}, (onError != null)?onError:doApiError);
		}
		
		public function showSettingsBox(access: uint, _handle: Function): void {
			callJS('showSettingsBox', 'onSettingsChanged', _handle, access);
		}
		
		public function showInviteBox(): void {
			callJS('showInviteBox', '', null);
		}
		
		public function getUserSettings(_handle: Function): void {
			callAPI('getUserSettings', null, _handle);
		}		
		
		public function getAlbums(a_uid: String, handler_: Function, onError: Function=null): void {
			callAPI('photos.getAlbums', {uid: a_uid}, function(data: Object): void {
				handler_(data);
			}, onError); 
		}
		
		public function getPhotos(a_uid: String, a_aid: String, handler_:*): void {
			callAPI('photos.get', {uid: a_uid, aid: a_aid}, handler_); 
		}
		
	    public function getAllFriends(uid: String, handler_:*, queryID:String='getAllFriends'): void {
			callAPI('friends.get', 
				{fields: 'uid,first_name,last_name,nickname,sex,bdate,photo,photo_medium,photo_big'},
//				{ext:1}, 
			handler_); 
	    }

	    override public function getProfiles(a_uids: String, handler_:*, a_fields: String='uid,first_name,last_name,nickname,sex,bdate,photo,photo_medium,photo_big', queryID:String=''): void {
			callAPI('getProfiles', {uids: a_uids, fields: a_fields}, function(list: Array): void {
				list.forEach(function(item: Object, i: int, arr: Array): void {
					if (item.uid)
						list[i].link = 'http://vkontakte.ru/id' + viewer_id + '#/id' + item.uid;
				});
				handler_(list);
			}); 
	    }
	    
	    public function getAppUsers(handler_:*): void {
			callAPI('friends.getAppUsers', null, handler_); 
	    }
	    
	    public function uploadToAlbum(a_aid: uint, fileName: String, jpgData: ByteArray, handler: Function): void {
	    	callAPI('photos.getUploadServer', {
	    		aid: a_aid
	    	}, function(data: Object): void {
	    		if (data.upload_url) {
	    			
					sroot.dispatchEvent(new GDataEvent(GDataEvent.REQUEST, null));
	    			function onUploadComplete(e: Event): void {
						var resultLoader: MultipartURLLoader = MultipartURLLoader(e.target);
						var data:* = getResponseData(resultLoader.loader.data);
			    		if (data) {
			    			callAPI('photos.save', {
			    				aid: a_aid,
			    				server: data.server,
			    				photos_list: data.photos_list,
			    				hash: data.hash
			    			}, handler);
	    				}
	    				sroot.dispatchEvent(new GDataEvent(GDataEvent.RESPONSE, null));
	    			}
	    			var mll: MultipartURLLoader = new MultipartURLLoader();
	    			mll.addEventListener(Event.COMPLETE, onUploadComplete);
	                mll.addFile(jpgData, fileName, "file1");
	                mll.load(data.upload_url);
	    		}
	    	});
	    }

	    public function uploadToWall(a_uid: uint, fileName: String, msg: String, jpgData: ByteArray, handler: Function): void {
	    	callAPI('photos.getWallUploadServer', {
	    		uid: a_uid
	    	}, function(data: Object): void {
	    		if (data.upload_url) {
	    			
					sroot.dispatchEvent(new GDataEvent(GDataEvent.REQUEST, null));
	    			function onUploadComplete(e: Event): void {
						var resultLoader: MultipartURLLoader = MultipartURLLoader(e.target);
						var data:* = getResponseData(resultLoader.loader.data);
			    		if (data) {
			    			callAPI('photos.saveWallPhoto', {
			    				uid: a_uid,
			    				server: data.server,
			    				photo: data.photo,
			    				hash: data.hash
			    			}, function(data: Object): void {
			    				callAPI('wall.post', {
				    				owner_id	: a_uid,
				    				message		: msg,
				    				attachment	: data[0].id
			    				}, handler);
			    			});
	    				}
	    				sroot.dispatchEvent(new GDataEvent(GDataEvent.RESPONSE, null));
	    			}
	    			var mll: MultipartURLLoader = new MultipartURLLoader();
	    			mll.addEventListener(Event.COMPLETE, onUploadComplete);
	                mll.addFile(jpgData, fileName, "photo");
	                mll.load(data.upload_url);
	    		}
	    	});
	    }
	}
}